import React, { useState, useRef, useEffect } from 'react';
import { Modal, InputNumber, Button, Row, Col, Space } from 'antd';
import { v4 as uuidv4 } from 'uuid';
import './index.less';

const XComponents = (props) => {
    const { xList = [], val, children, gd = false } = props;
    if (xList.includes(val)) {
        return (
            <div className='SeatMapModal_seat_x'>
                {children}
                {gd && <div className='SeatMapModal_seat_xConponents'></div>}
            </div>
        );
    }
    return children;
};

const SeatEditor = (props) => {
    const { visible = {}, onClose, seatIdList, onOk } = props;
    const { show, detail } = visible;
    const [data, setData] = useState({
        rowCount: 10,
        ColCount: 10,
        list: [],
        xList: [],
        yList: []
    });
    const [checkIdList, setCheckIdList] = useState([]);

    // 新增框选相关状态
    const containerRef = useRef(null);
    const [isDragging, setIsDragging] = useState(false);
    const [startPos, setStartPos] = useState({ x: 0, y: 0 });
    const [currentPos, setCurrentPos] = useState({ x: 0, y: 0 });
    const [clickDisabled, setClickDisabled] = useState(false);
    useEffect(() => {
        if (show) {
            setData(detail);
            setCheckIdList(seatIdList);
        } else {
            setData({});
            setCheckIdList([]);
        }
    }, [show]);

    const getRelativePos = (event) => {
        const rect = containerRef.current.getBoundingClientRect();
        return {
            x: event.clientX - rect.left,
            y: event.clientY - rect.top
        };
    };

    const handleMouseDown = (e) => {
        if (e.button !== 0) return;

        const pos = getRelativePos(e);
        // 检查是否点击在座位元素上
        const elements = document.elementsFromPoint(e.clientX, e.clientY);
        const isClickOnSeat = elements.some(el => el.hasAttribute('data-seat-id'));

        if (!isClickOnSeat) {
            setIsDragging(true);
            setStartPos(pos);
            setCurrentPos(pos);
            setClickDisabled(true);
        }
    };

    const handleMouseMove = (e) => {
        if (!isDragging) return;
        const pos = getRelativePos(e);
        setCurrentPos(pos);
    };

    const handleMouseUp = () => {
        if (isDragging) {
            setIsDragging(false);

            const minX = Math.min(startPos.x, currentPos.x);
            const maxX = Math.max(startPos.x, currentPos.x);
            const minY = Math.min(startPos.y, currentPos.y);
            const maxY = Math.max(startPos.y, currentPos.y);

            const selected = data.list.filter(seat => {
                const seatElement = document.querySelector(`[data-seat-id="${seat.id}"]`);
                if (!seatElement || seat.status !== 'available') return false;

                const rect = seatElement.getBoundingClientRect();
                const containerRect = containerRef.current.getBoundingClientRect();
                const seatX = rect.left - containerRect.left;
                const seatY = rect.top - containerRect.top;

                return (
                    seatX >= minX - 12 && // 12为座位元素半宽
                    seatX <= maxX + 12 &&
                    seatY >= minY - 12 && // 12为座位元素半高
                    seatY <= maxY + 12
                );
            });
            setCheckIdList(prev => [...new Set([...prev, ...selected.map(s => s.id)])])
        } else {

            setIsDragging(false);
            // 延迟恢复点击防止误触发
            setTimeout(() => setClickDisabled(false), 100);
        }



    };

    const onChange = (id) => {
        if (clickDisabled) return;
        setCheckIdList(prev =>
            prev.includes(id) ? prev.filter(i => i != id) : [...prev, id]
        );
    };

    const { ColCount, list = [], xList = [], yList = [] } = data;
    const ColLiner = [...new Set(list.map(val => val.y))];

    const RenderItemList = ({ data: yValue }) => {
        return (
            <div className='SeatMapModal_seat_list'>
                {list
                    .filter(val => val.y === yValue)
                    .map((val) => (
                        <div
                            key={val.id}
                            data-seat-id={val.id}
                            onClick={(e) => {
                                e.stopPropagation()
                                if (val.status !== 'none') {
                                    onChange(val.id)
                                }
                            }}
                            style={yList.includes(val.x) ? { marginRight: 24 } : {}}
                            className={`SeatMapModal_seat_listItem ${checkIdList.includes(val.id)
                                ? 'SeatMapModal_seat_listCheck'
                                : val.status === 'available'
                                    ? 'SeatMapModal_seat_listNoCheck'
                                    : ''
                                }`}
                        />
                    ))}
            </div>
        );
    };
    return (
        <Modal
            title="线下答疑座位排布"
            visible={show}
            width={800}
            onOk={() => {
                onOk(checkIdList);
                onClose();
            }}
            onCancel={onClose}
        >
            <div
                className='SeatMapModal_box'
                ref={containerRef}
                onMouseDown={handleMouseDown}
                onMouseMove={handleMouseMove}
                onMouseUp={handleMouseUp}
                onMouseLeave={handleMouseUp}
                style={{ cursor: isDragging ? 'crosshair' : 'default' }}
            >

                <div className='SeatMapModal_desc_box'>
                    这里是教室名称，共计{list.filter(val => val.status !== 'none').length}个座位
                </div>

                <div className='SeatMapModal_seat_setting'>
                    座位设置：
                    <div>
                        <Space>
                            <div className='SeatMapModal_seat_list'>
                                选中座位 <div className='SeatMapModal_seat_listItem SeatMapModal_seat_listCheck' />
                            </div>
                            <div className='SeatMapModal_seat_list'>
                                取消座位 <div className='SeatMapModal_seat_listItem SeatMapModal_seat_listNoCheck' />
                            </div>
                        </Space>

                        <div className='SeatMapModal_seat_list'>
                            <div className='SeatMapModal_seat_liner'>
                                {ColLiner.map((item, index) => (
                                    <XComponents key={index} val={index} xList={xList} yList={yList}>
                                        <div className='SeatMapModal_seat_count'>{item}</div>
                                    </XComponents>
                                ))}
                            </div>

                            <div style={{ position: 'relative' }}>
                                {yList.sort().map((val, index) => (
                                    val && (
                                        <div
                                            key={index}
                                            style={{ left: `${val * 26 + index * 18}px` }}
                                            className='SeatMapModal_seat_yComponents'
                                        />
                                    )
                                ))}

                                {ColLiner.map((val, index) => (
                                    <XComponents key={index} gd val={index} xList={xList} yList={yList}>
                                        <RenderItemList data={val} />
                                    </XComponents>
                                ))}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </Modal>
    );
};

export default SeatEditor;